package com.anti.modular.bus.housebilldetail.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.anti.commom.core.utils.DecimalUtils;
import com.anti.core.context.login.LoginContextHolder;
import com.anti.jdbc.DBUtils;
import com.anti.jdbc.support.page.PageParam;
import com.anti.jdbc.support.page.PageResult;
import com.anti.commom.core.exception.BusinessException;
import com.anti.modular.bus.busbasicsettings.entity.BusBasicSettings;
import com.anti.modular.bus.busbasicsettings.service.BusBasicSettingsService;
import com.anti.modular.bus.housebill.entity.HouseBill;
import com.anti.modular.bus.housebilldetail.entity.HouseBillDetail;
import com.anti.modular.bus.housebilldetail.enums.HouseBillDetailExceptionEnum;
import com.anti.modular.bus.housebilldetail.param.HouseBillDetailParam;
import com.anti.modular.bus.housebilldetail.result.BillDetailForEditResult;
import com.anti.modular.bus.housebilldetail.result.HouseBillDetailResult;
import com.anti.modular.bus.housebilldetail.service.HouseBillDetailService;
import com.anti.modular.bus.houselease.entity.HouseLease;
import com.anti.modular.bus.houselease.service.HouseLeaseService;
import com.anti.modular.commonutils.CalculateQs;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 账单详情service接口实现类
 *
 * @author anti
 * @date 2021-05-07 09:59:49
 */
@Service
public class HouseBillDetailServiceImpl implements HouseBillDetailService {
    @Resource
    DBUtils dbUtils;
    @Resource
    HouseLeaseService houseLeaseService;
    @Resource
    BusBasicSettingsService busBasicSettingsService;

    @Override
    public HouseBillDetail getById(HouseBillDetailParam houseBillDetailParam){
        String sql="select * from house_bill_detail where id =? ";
        return dbUtils.get(sql,HouseBillDetail.class,houseBillDetailParam.getId());
    }

    @Override
    public PageResult page(PageParam pageParam,HouseBillDetailParam houseBillDetailParam) {
        StringBuilder sb=new StringBuilder("select * from house_bill_detail where 1=1 ");
        ArrayList<Object> param = CollectionUtil.newArrayList();
        if (ObjectUtil.isNotNull(houseBillDetailParam)) {
            // 根据費用類別 查询
            if (ObjectUtil.isNotEmpty(houseBillDetailParam.getRentAmountCategory())) {
               sb.append(" and rent_amount_category = ?");
               param.add(houseBillDetailParam.getRentAmountCategory());
            }
        }
        return dbUtils.query(pageParam,sb.toString(),param.toArray());
    }

    @Override
    public List<HouseBillDetail> list(HouseBillDetailParam houseBillDetailParam) {
        String sql="";
        return dbUtils.query(sql,HouseBillDetail.class);
    }

    @Override
    public List<HouseBillDetailResult> getListById(Long houseBillId) {
        String sql="select * from house_bill_detail where  house_bill_id=? and rent_amount_type =1 and status =0";
        List<HouseBillDetailResult> houseBillDetails = dbUtils.query(sql, HouseBillDetailResult.class, houseBillId);
        return houseBillDetails;
    }

    @Override
    public List<HouseBillDetail> getListByIdAndType(Long houseBillId, int type) {
        StringBuilder sql=new StringBuilder("select * from house_bill_detail where  house_bill_id=?  and status =0");
        if (type==1){
            sql.append(" and deposit_hydropower_flag in (1,2,3)");
        }else if (type==2){
            sql.append(" and deposit_hydropower_flag = 4");
        }else if (type==3){
            sql.append(" and deposit_hydropower_flag = 5");
        }
        List<HouseBillDetail> houseBillDetails = dbUtils.query(sql.toString(), HouseBillDetail.class, houseBillId);
        return houseBillDetails;
    }

    @Override
    public List<HouseBillDetail> getNoCbListById(Long houseBillId) {
        String sql="select * from house_bill_detail where  house_bill_id=? and rent_amount_type =0 and status =0";
        List<HouseBillDetail> houseBillDetails = dbUtils.query(sql, HouseBillDetail.class, houseBillId);
        return houseBillDetails;
    }

    @Override
    public BigDecimal getXIaojiById(Long houseBillId) {
        String sql="select sum(amount) from house_bill_detail where  house_bill_id=? and status =0";
        Double houseBillDetails = dbUtils.getFirst(sql, Double.class, houseBillId);
        return DecimalUtils.toBigDecimal(houseBillDetails);
    }

    @Override
    public List<HouseBillDetailResult> getListByIdWithNoXz(Long houseBillId) {
        String sql="select * from house_bill_detail where  house_bill_id=? and status =0";
        List<HouseBillDetailResult> houseBillDetails = dbUtils.query(sql, HouseBillDetailResult.class, houseBillId);
        return houseBillDetails;
    }

    @Override
    public void add(HouseBillDetailParam houseBillDetailParam) {
        HouseBillDetail houseBillDetail = new HouseBillDetail();
        BeanUtil.copyProperties(houseBillDetailParam, houseBillDetail);
        dbUtils.insert(houseBillDetail);
    }

    @Override
    public Long add(HouseBillDetail houseBillDetail) {
        String s = dbUtils.insertKey(houseBillDetail).toString();
        return Long.parseLong(s);
    }

    @Override
    public void addYdDetail(Long billPk, Long reservationId, BigDecimal deposit, Date date, Long sysLoginUserId) {
        HouseBillDetail houseBillDetail =new HouseBillDetail();
        houseBillDetail.setHouseBillId(billPk);
        houseBillDetail.setAmount(deposit.negate());
        houseBillDetail.setBillInOutType(2);
        //押金 1  水電 2  3 （租金、4临时收入、5临时支出 6其他）
        houseBillDetail.setDepositHydropowerFlag(6);
        houseBillDetail.setRentAmountCategory(reservationId);
        houseBillDetail.setRentAmountName("定金對沖");
        //費用類型（字典  1抄表 0不抄表） 抄表需要
        houseBillDetail.setRentAmountType(0);
        houseBillDetail.setStatus(0);
        houseBillDetail.setCreateTime(date);
        houseBillDetail.setCreateUser(sysLoginUserId);
        this.add(houseBillDetail);
    }

    public void delete(HouseBillDetailParam houseBillDetailParam) {
        String sql="delete  from house_bill_detail where id =? ";
        dbUtils.execSql(sql,houseBillDetailParam.getId());
    }

    @Override
    public void deleteByBillIdAndType(Long billId, int type) {
        String sql="delete from house_bill_detail where house_bill_id =? and deposit_hydropower_flag=?";
        dbUtils.execSql(sql,billId,type);
    }

    public void edit(HouseBillDetailParam houseBillDetailParam) {
        HouseBillDetail houseBillDetail = this.queryHouseBillDetail(houseBillDetailParam);
        BeanUtil.copyProperties(houseBillDetailParam, houseBillDetail);
        dbUtils.update(houseBillDetail);
    }

    @Override
    public void editBillDetailByLeaseIdAndQsNum(Long leaseId, int qsNum,BigDecimal decimal) {
        String ch="select * from house_bill where house_lease_id=? and qsnum=? and bill_status = 0 and status=0";
        HouseBill first = dbUtils.getFirst(ch, HouseBill.class, leaseId, qsNum);
        if (null != first){
            HouseLease leaseId1 = houseLeaseService.getByLeaseId(first.getHouseLeaseId());
            //基础设置
            BusBasicSettings one = busBasicSettingsService.getOne();
            //计算费用时月天数 （字典 0按固定30天算 1按月份实际天数
            int calculateStyle = one.getCalculateStyle();
            //账单金额取整 （字典 0关闭 1打开 小数点后四舍五入）
            int amount = one.getAmount();
            String de="select * from house_bill_detail where house_bill_id =? and status=0 and deposit_hydropower_flag=3";
            HouseBillDetail detail = dbUtils.getFirst(de, HouseBillDetail.class, first.getId());
            if(detail!=null){
                BigDecimal rent = CalculateQs.getRentMoney(amount,calculateStyle, leaseId1.getReceiptFu(),
                        leaseId1.getReceiptYj(),first.getRentStartDate(),first.getRentEndDate(),decimal);
                detail.setAmount(rent);
                detail.setUpdateUser(LoginContextHolder.me().getSysLoginUserId());
                detail.setUpdateTime(new Date());
                dbUtils.update(detail);
            }
        }
    }

    @Override
    public void editJe(HouseBillDetailParam houseBillDetailParam) {
        HouseBillDetail houseBillDetail = this.queryHouseBillDetail(houseBillDetailParam);
        houseBillDetail.setAmount(houseBillDetailParam.getAmount());
        houseBillDetail.setUpdateTime(new Date());
        houseBillDetail.setUpdateUser(LoginContextHolder.me().getSysLoginUserId());
        dbUtils.update(houseBillDetail);
    }

    @Override
    public HouseBillDetail detail(HouseBillDetailParam houseBillDetailParam) {
        return this.queryHouseBillDetail(houseBillDetailParam);
    }

    /**
     *
     * @param billId
     * @param type 1 正常查询 2 退租清算查询
     * @return
     */
    @Override
    public BillDetailForEditResult detailByBillId(Long billId,int type) {
        String getBillSql="select * from house_bill where id =? ";
        BillDetailForEditResult first = dbUtils.getFirst(getBillSql, BillDetailForEditResult.class, billId);
        String getCbFySql="select a.*,IFNULL(c.solder,0.00)  as solder,IFNULL(c.id,0)  as cbflag,IFNULL(c.amount,0)  as amountDu,IFNULL(c.dosage,0) as dosage ,IFNULL(c.pre_reading,0) as pre_reading , IFNULL(c.reading,0) as reading from house_bill_detail a  LEFT JOIN hydropower_meter c on a.id=c.house_bill_detail_id where a.house_bill_id=? and a.status=0 and  a.rent_amount_type=1 and a.deposit_hydropower_flag=2";
        List<HouseBillDetailResult> cbList = dbUtils.query(getCbFySql, HouseBillDetailResult.class, billId);
        first.setCbfy(cbList);
        String getgdFySql="select a.* from house_bill_detail a where a.house_bill_id=? and a.status=0 and  a.rent_amount_type=0  and a.deposit_hydropower_flag=2";
        List<HouseBillDetailResult> gdList = dbUtils.query(getgdFySql, HouseBillDetailResult.class, billId);
        first.setSdtx(gdList);
        String getLssrSql="select a.* from house_bill_detail a where a.house_bill_id=? and a.status=0  and a.deposit_hydropower_flag=4";
        List<HouseBillDetailResult> lssrList = dbUtils.query(getLssrSql, HouseBillDetailResult.class, billId);
        first.setLssr(lssrList);
        String getLszcFySql="select a.*, abs(a.amount) as absAmount  from house_bill_detail a where a.house_bill_id=? and a.status=0  and a.deposit_hydropower_flag=5";
        List<HouseBillDetailResult> lszcList = dbUtils.query(getLszcFySql, HouseBillDetailResult.class, billId);
        for (int i = 0; i < lszcList.size(); i++) {
            String amount = lszcList.get(i).getAbsAmount();
            lszcList.get(i).setAmount(amount);
        }
        first.setLszc(lszcList);
        if (type == 2) {
            String getYjSql="select a.*,abs(a.amount) as absAmount from house_bill_detail a where a.house_bill_id=? and a.status=0 and  a.rent_amount_type=0  and  a.deposit_hydropower_flag in (1,3)";
            List<HouseBillDetailResult> getYjSqlList = dbUtils.query(getYjSql, HouseBillDetailResult.class, billId);
            for (int i = 0; i < getYjSqlList.size(); i++) {
                String amount = getYjSqlList.get(i).getAbsAmount();
                getYjSqlList.get(i).setAmount(amount);
            }
            first.setYjList(getYjSqlList);
        }
        return first;
    }

    /**
     * 获取账单详情
     *
     * @author anti
     * @date 2021-05-07 09:59:49
     */
    private HouseBillDetail queryHouseBillDetail(HouseBillDetailParam houseBillDetailParam) {
        HouseBillDetail houseBillDetail = this.getById(houseBillDetailParam);
        if (ObjectUtil.isNull(houseBillDetail)) {
            throw new BusinessException(HouseBillDetailExceptionEnum.NOT_EXIST);
        }
        return houseBillDetail;
    }


}
